package eu.gegenleitner.esspacc.communication;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

public class HttpRequester {

	private String url;
	private CloseableHttpClient httpClient;
	
	public HttpRequester(String url) {
		this.url = url;
		BasicCookieStore cookieStore = new BasicCookieStore();
		httpClient = HttpClients.custom()
				.setDefaultCookieStore(cookieStore)
				.build();
	}
	
	public String sendCSRToService(String signedCSR) throws ClientProtocolException, IOException, URISyntaxException {
		return sendKeyValuePairAsPostToService("zea", signedCSR);
	}
	
	public String sendTokenFromEMail(String token) throws ClientProtocolException, IOException, URISyntaxException {
		return sendKeyValuePairAsPostToService("token", token);
	}
	
	private String sendKeyValuePairAsPostToService(String key, String value) throws ClientProtocolException, IOException, URISyntaxException {
		RequestBuilder rBuilder = RequestBuilder.post();
		rBuilder.setUri(new URI(url));
		rBuilder.addParameter(key, value);
		HttpUriRequest req = rBuilder.build();
		
		CloseableHttpResponse response = httpClient.execute(req);
		HttpEntity entity = response.getEntity();
		String responseString = EntityUtils.toString(entity);
		EntityUtils.consume(entity);
		response.close();
		return responseString;
	}

	public void close() {
		try {
			httpClient.close();
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
}
